import subprocess
import os


def truncate_all_container_logs():
    try:
        # 获取所有容器的 ID
        container_ids = subprocess.check_output(
            ['docker', 'ps', '-a', '-q'],
            text=True
        ).strip().splitlines()

        for container_id in container_ids:
            # 获取容器日志文件路径
            inspect_output = subprocess.check_output(
                ['docker', 'inspect', '--format', '{{.LogPath}}', container_id],
                text=True
            ).strip()

            if os.path.exists(inspect_output):
                # 截断日志文件
                with open(inspect_output, 'w') as log_file:
                    pass

                print(f"日志文件 {inspect_output} 已截断。")
            else:
                print(f"日志文件 {inspect_output} 不存在。")

    except subprocess.CalledProcessError as e:
        print(f"发生错误: {e}")
    except Exception as e:
        print(f"发生错误: {e}")


# 示例用法
truncate_all_container_logs()
